package imp

import (
	sqlc "bgs/db/sqlc"
	storeFanGrpc "bgs/grpc/gen/service/store_fan"
	"bgs/grpc/gen/shared/message"
	"context"
	"fmt"
)

/****************************************************************************************/
/*                               store_fan entity of helper                              */
/****************************************************************************************/

func transformStoreFanEntityToPb(storeFan sqlc.StoreFan) *storeFanGrpc.StoreFanEntity {
	return &storeFanGrpc.StoreFanEntity{
		Id:             storeFan.ID,
		StoreId:        storeFan.StoreID,
		FollowerUserId: storeFan.FollowerUserID,
		BeFollowed:     sqlc.GoTimeToPBTimestamp(storeFan.BeFollowed),
		AliasName:      storeFan.AliasName,
		Remark:         storeFan.Remark.String,
	}
}

/****************************************************************************************/
/*                               store_fan entity of cmd                                 */
/****************************************************************************************/

// UpsertStoreFan 创建品牌粉丝关系
func (s *StoreAPIService) UpsertStoreFan(ctx context.Context, req *storeFanGrpc.UpsertStoreFanRequest) (res *storeFanGrpc.UpsertStoreFanResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("store_fanImp->UpsertStoreFan:%v", req)
	res = &storeFanGrpc.UpsertStoreFanResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	arg := sqlc.UpsertStoreFanParams{
		StoreID:        req.StoreId,
		FollowerUserID: req.FollowerUserId,
		BeFollowed:     sqlc.PBTimestampToGoTime(req.BeFollowed),
		AliasName:      req.AliasName,
	}
	storeFan, err := s.dao.Q.UpsertStoreFan(ctx, arg)

	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	res.StoreFan = transformStoreFanEntityToPb(storeFan)
	return
}

// UpdateStoreFan 更新品牌粉丝关系
func (s *StoreAPIService) UpdateStoreFan(ctx context.Context, req *storeFanGrpc.UpdateStoreFanRequest) (res *storeFanGrpc.UpdateStoreFanResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("store_fanImp->UpdateStoreFan:%v", req)
	res = &storeFanGrpc.UpdateStoreFanResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	arg := sqlc.UpdateStoreFanParams{
		ID:        req.Id,
		AliasName: req.AliasName,
		Remark:    sqlc.NSFromString(req.Remark),
	}
	storeFan, err := s.dao.Q.UpdateStoreFan(ctx, arg)
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	res.StoreFan = transformStoreFanEntityToPb(storeFan)
	return
}

/****************************************************************************************/
/*                               store_fan entity of query                               */
/****************************************************************************************/

// GetStoreFan 获取单个品牌粉丝
func (s *StoreAPIService) GetStoreFan(ctx context.Context, req *storeFanGrpc.GetStoreFanRequest) (res *storeFanGrpc.GetStoreFanResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("store_fanImp->GetStoreFan:%v", req)
	res = &storeFanGrpc.GetStoreFanResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	storeFan, err := s.dao.Q.GetStoreFan(ctx, req.Id)
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	res.StoreFan = transformStoreFanEntityToPb(storeFan)
	return
}

/****************************************************************************************/
/*                            store_fanJoins entity of helper                           */
/****************************************************************************************/

func transformStoreFanWithUserStatEntityToPb(row sqlc.ListStoreFanWithUserAndUserStatsRow) *storeFanGrpc.StoreFanWithUserAndUserStatEntity {
	return &storeFanGrpc.StoreFanWithUserAndUserStatEntity{
		// store_fan
		Id:             row.ID,
		StoreId:        row.StoreID,
		FollowerUserId: row.FollowerUserID,
		BeFollowed:     sqlc.GoTimeToPBTimestamp(row.BeFollowed),
		AliasName:      row.AliasName,
		Remark:         row.Remark.String,

		// user
		FollowerUserNickName: row.FollowerUserNickName,
		FollowerUserPic:      row.FollowerUserPic,

		// user_stat
		FansCount:            row.FansCount,
		FollowUserCount:      row.FollowUserCount,
		FollowBrandCount:     row.FollowBrandCount,
		FollowStoreCount:     row.FollowStoreCount,
		EndorseBrandCount:    row.EndorseBrandCount,
		EndorseStoreCount:    row.EndorseStoreCount,
		EndorseActivityCount: row.EndorseActivityCount,
		InvolveActivityCount: row.InvolveActivityCount,
		OrderCount:           row.OrderCount,
		ViewCount:            row.ViewCount,
		PayAmount:            row.PayAmount,
	}
}

func mapStoreFanWithUserAndUserStatEntityToPb(list []sqlc.ListStoreFanWithUserAndUserStatsRow, f func(sqlc.ListStoreFanWithUserAndUserStatsRow) *storeFanGrpc.StoreFanWithUserAndUserStatEntity) []*storeFanGrpc.StoreFanWithUserAndUserStatEntity {
	r := make([]*storeFanGrpc.StoreFanWithUserAndUserStatEntity, len(list))
	for i, item := range list {
		r[i] = f(item)
	}
	return r
}

/****************************************************************************************/
/*                            store_fanJoins entity of query                             */
/****************************************************************************************/

// ListStoreFanWithUserAndUserStats  获取粉丝及用户和其统计信息
func (s *StoreAPIService) ListStoreFanWithUserAndUserStats(ctx context.Context, req *storeFanGrpc.ListStoreFanWithUserAndUserStatsRequest) (res *storeFanGrpc.ListStoreFanWithUserAndUserStatsResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("store_fanImp->ListStoreFanWithUserAndUserStats:%v", req)

	res = &storeFanGrpc.ListStoreFanWithUserAndUserStatsResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}

	q := s.dao.Q
	ts := sqlc.PBTimestampToGoTime(req.Ts)
	storeID := req.StoreId
	keyword := req.Keyword
	isKeywordEmpty := keyword == ""
	keywordLike := fmt.Sprintf("%%%s%%", keyword)

	total, err := q.CountStoreFanWithUserAndUserStats(ctx, sqlc.CountStoreFanWithUserAndUserStatsParams{
		Created:        ts,
		StoreID:        storeID,
		IsKeywordEmpty: isKeywordEmpty,
		Keyword:        keywordLike,
	})
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	if total == 0 {
		// 不用继续调用listfunc
		return
	}

	storeFanWithUserAndUserStats, err := q.ListStoreFanWithUserAndUserStats(ctx, sqlc.ListStoreFanWithUserAndUserStatsParams{
		Limit:          req.Limit,
		Offset:         req.Offset,
		Created:        ts,
		StoreID:        storeID,
		IsKeywordEmpty: isKeywordEmpty,
		Keyword:        keywordLike,
	})
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	res.Total = total
	res.StoreFanWithUserStats = mapStoreFanWithUserAndUserStatEntityToPb(storeFanWithUserAndUserStats, transformStoreFanWithUserStatEntityToPb)
	return
}
